<?php
/**
 * 用户登陆注册，注销
 * author:ty
 * date:2017/08/21
 */
namespace App\Http\Controllers;

use App\Http\Models\User;
use Illuminate\Http\Request;
use App\Http\Util\Image;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Validator;

class LoginController extends Controller
{
    /**注册*/
    public function register()
    {
        return view('login.register');
    }

    /**注册处理*/
    public function doregister(Request $request)
    {
        $input = Input::all();
        $phone = trim($input['phone']);
        $param=[
            'phone' => trim($input['phone']),
            'password' => trim($input['password']),
            'password_confirmation' => trim($input['repassword']),
            'remember_token' => trim($input['_token']),
            'mscode' => trim($input['mscode'])
        ];

        $rules=[
            'phone' => 'required|regex:/^1[34578][0-9]{9}$/',
            'password' => 'required|between:6,20|confirmed',
            'mscode' => 'required|max:6'
        ];

        $message = [
            'phone.required' => '手机号必填!',
            'phone.regex' => '请输入正确手机号!',
            'password.required' => '登陆密码必填!',
            'password.between' => '登陆密码要在6到20为之间!',
            'password.confirmed' => '两次密码不一致!',
            'mscode.required' => '短信验证码必填!',
            'mscode.max' => '短信验证码不能超过6位!',
        ];

        $validator = Validator::make($param,$rules,$message);
       if ($validator->fails()) {
           return back()->withErrors($validator)->withInput();
        }
        /**d短信验证码校验*/
        if(isset($_COOKIE['phonemsg'])){
            if($param['mscode'] != $_COOKIE['phonemsg'])
            return back()->withErrors('短信验证码错误!')->withInput();
        }else{
            return back()->withErrors('验证码过期或没有发送请求,请重新发送!')->withInput();
        }
        /**验证注册手机号是否在系统可用状态*/
        $usersql = DB::table('frontusers')//->where('status',1)
             ->where(function ($query) use ($phone){
                $query->where('phone',$phone);
            })->first();
        if(!empty($usersql)){
            return back()->withErrors('手机号已存在!')->withInput();
        }

        $id = DB::table('frontusers')->insertGetId([
            'name'=>$param['phone'],
            'phone' => $param['phone'],
            'leve' => '1',
            'password' => Hash::make($param['password']),
            'remember_token' => $param['remember_token'],
            'status' => 1,
            'created_at' => date('Y-m-d H:i:s',time()),
            'updated_at' => date('Y-m-d H:i:s',time())
        ]);

        if(!$id){
             return back()->withErrors('注册失败!请联系客服或重新注册!')->withInput();
        }else{
            $user = User::find($id);
            Session::put('user',$user);
            return redirect('/user');
        }

    }

    /**登陆*/
    public function login()
    {
        if(isset($_COOKIE['userid']) && $_COOKIE['userid'] != ''){
            $res = User::where('id',$_COOKIE['userid'])->where('status',1)->first();
            Session::put('user',$res);
            return redirect('/');
        }
        return view('login.login');
    }

    /**登陆处理*/
    public function dologin(Request $request)
    {
        $data = Input::all();
        $param = [
            'email' => trim($data['email']),
            'password' => trim($data['password']),
            'remember' => trim(Input::get('remember'))
        ];

        /**校验是手机登陆还是邮箱登陆*/
        if(preg_match("/^1[34578]{1}\d{9}$/",$param['email'])){
            $userNo = 'phone';
            $rules = [
                'email' => 'required|exists:frontusers,phone',
                'password'=>'required'
            ];
            $message = [
                'email.required' => '请填写登陆账号名!',
                'email.exists' => '账号不存在!',
                'password.required' => '请填写密码!'
            ];
        }else{
            $userNo = 'email';
            $rules = [
                'email' => 'required|exists:frontusers,email|regex:/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/',
                'password'=>'required'
            ];
            $message = [
                'email.required' => '请填写登陆账号名!',
                'email.exists' => '账号不存在!',
                'email.regex' => '邮箱账号格式错误!',
                'password.required' => '请填写密码!'
            ];
        }
        /**登陆信息基础校验*/
        $validator = Validator::make($param,$rules,$message);
        if($validator->fails()){
            return back()->withErrors($validator);
        }
        /**数据库校验*/
        $res = DB::table('frontusers')->where($userNo,$param['email'])->where('status',1)->first();
        if(!$res){
            return back()->withErrors('该账号被禁用,请联系官网!')->withInput();
        }
        if(!Hash::check($param['password'],$res->password)) {
            return back()->withErrors('密码不正确')->withInput();
        }

        Session::put('user',$res);
        /**判断是否有记住密码操作*/
        if($param['remember']){
            setcookie("userid", session('user')->id,time()+3600*24*30);
        }
        return redirect('/');

    }

    /**找回密码*/
    public function forgetpw()
    {
        return view('login.forgetpw');
    }

    /**重置密码*/
    public function resetpw()
    {
        $input = Input::all();
        $phone = trim($input['phone']);
        $param=[
            'phone' => $phone,
            'mscode' => trim($input['mscode'])
        ];
        if(!count($param)>1){
            return view('errors.404');
        }
        $rules = [
            'phone' => 'required|regex:/^1[34578][0-9]{9}$/',
            'mscode' => 'required|max:6'
        ];
        $message = [
            'phone.required' => '手机号必填!',
            'phone.regex' => '请输入正确手机号!',
            'mscode.required' => '短信验证码必填!',
            'mscode.max' => '短信验证码不大于6位数字!',
        ];

        $validator = Validator::make($param,$rules,$message);
        if($validator->fails()){
            return back()->withErrors($validator);
        }
        /**d短信验证码校验*/
       if(isset($_COOKIE['phonemsg'])){
            if($param['mscode'] != $_COOKIE['phonemsg'])
                return back()->withErrors('短信验证码错误!')->withInput();
        }else{
            return back()->withErrors('验证码过期或没有发送请求,请重新发送!')->withInput();
        }
        /**验证手机号是否在系统中*/
        $isempty = DB::table('frontusers')->where('status',1)
            ->where(function ($query) use ($phone){
                $query->where('phone',$phone);
            })->first();
        if(empty($isempty)){
            return back()->withErrors('账号不存在!')->withInput();
        }
        $param['user']['phone']=$phone;
        return view('login.resetpw',['param'=>$param]);
    }

    /**重置密码保存*/
    public function storepw()
    {
        $param = [
            'password' => trim(Input::get('password')),
            'enpassword' => trim(Input::get('enpassword')),
            'phone' => trim(Input::get('phone'))
        ];
        if($param['password'] != $param['enpassword']){
            echo '<script>alert("两次密码不一致")</script>';return false;
        }
        $res = DB::table('frontusers')
            ->where('phone',$param['phone'])
            ->update(['password'=>Hash::make($param['password']),'updated_at'=>date('Y-m-d H:i:s',time())]);
        if($res){
            return redirect('/login');
        }else{
            echo '<script>alert("密码修改失败!请重试")</script>';return false;
        }
    }

    /**注销*/
    public function loginout()
    {
        setcookie("userid", session('user')->id,time()-1);
        Session::forget('user');
        return redirect('/login');
    }

    /**验证码提取*/
    public function code()
    {
        $code = new Image();
        return $code->buildImageVerify();
    }

}
